﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace DIProject.ReceptionGoods
{
    public partial class SZForm : Form
    {
        public SZForm()
        {
            InitializeComponent();
        }

        private void SZForm_Load(object sender, EventArgs e)
        {
            DataSets.SettingsTableAdapters.ContragentsTableAdapter adapter = new DIProject.DataSets.SettingsTableAdapters.ContragentsTableAdapter();
            DataSets.Settings.ContragentsDataTable cdt = adapter.GetData();
            DataSets.Settings.ContragentsRow cr = cdt.NewContragentsRow();
            cr.Id = Int32.MinValue;
            cr.Name = "Выбирите поставщика";
            
            cdt.Rows.InsertAt(cr, 0);
            this.ddlSellers.ComboBox.DisplayMember = "Name";
            this.ddlSellers.ComboBox.ValueMember = "Id";
            this.ddlSellers.ComboBox.DataSource = cdt;
            cbSelRows.ComboBox.SelectedIndex = 0;
        }

        private void ddlSellers_SelectedIndexChanged(object sender, EventArgs e)
        {
            ToolStripComboBox tscb = sender as ToolStripComboBox;
            ComboBox cb = tscb.ComboBox;
            Int32 tmp = (Int32)cb.SelectedValue;
            if (tmp == Int32.MinValue)
                return;
            DataSets.waybillsDataTableAdapters.SZDataTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.SZDataTableAdapter();
            DataSets.waybillsData.SZDataDataTable dt = adapter.GetData(tmp);
            DataSets.waybillsData.SZDataRow dr = dt.NewSZDataRow();
            dr.Id = Int32.MinValue;
            dr.ContragentDocNumber = "Ваберите накладную";
            dt.Rows.InsertAt(dr, 0);
            lbNkldList.ValueMember = "Id";
            lbNkldList.DisplayMember = "ContragentDocNumber";
            lbNkldList.DataSource = dt;
        }

        private void lbNkldList_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListBox lb = sender as ListBox;
            Int32 tmp = (Int32)lb.SelectedValue;
            if(tmp == Int32.MinValue)
            {
                //MessageBox.Show("Выберите накладную");
                return;
            }
            DataSets.waybillsDataTableAdapters.SZDataDetailTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.SZDataDetailTableAdapter();
            DataSets.waybillsData.SZDataDetailDataTable dt = adapter.GetData(tmp);
            dgvPartiesList.DataSource = dt;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            List<Int32> partyIDs = new List<int>();
            if (cbSelRows.SelectedIndex == 0)
            {
                foreach (DataGridViewRow row in dgvPartiesList.Rows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    Int32 i = dr.PartyId;
                    partyIDs.Add(i);
                }
            }
            else
            {
                if (dgvPartiesList.SelectedRows.Count < 1)
                {
                    MessageBox.Show("Требуется выделить хотябы одну строку", "Выделите строку", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                foreach (DataGridViewRow row in dgvPartiesList.SelectedRows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    Int32 i = dr.PartyId;
                    partyIDs.Add(i);
                }
            }
            string str = CreateXML(partyIDs).OuterXml;            
            ReceptionGoods.SZFormRPT szForm = new SZFormRPT(CreateXML(partyIDs).OuterXml);
            szForm.Show();
            
        }
        private XmlNode CreateXML(List<Int32> partyIDs)
        {
            if (partyIDs.Count < 1)
                throw new Util.DIException("Ошибка! Нужно одну или более строк выбрать!");
            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.CreateElement("r");
            doc.AppendChild(root);
            foreach (Int32 i in partyIDs)
            {
                XmlElement item = doc.CreateElement("i");
                XmlAttribute val = doc.CreateAttribute("v");
                val.InnerText = i.ToString();
                item.Attributes.Append(val);
                root.AppendChild(item);
            }
            return doc;
        }
        /// <summary>
        /// печать штрих кодов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Util.SettingFile sf = Util.Setting2.GetSetting();
            switch (sf.BarcodePrinter)
            {
                case DIProject.Util.BarCodePrinterType.BZB:
                    ShtrihProcess();
                    break;
                case DIProject.Util.BarCodePrinterType.ZEBRA:
                    ZebraShtrihProcess();
                    break;
                default:
                    ErrorPrintBarCode();
                    break;
            }
            
        }
        private void ErrorPrintBarCode()
        {
            MessageBox.Show("Не задан принтер штрихэтикеток");
        }
        private void ZebraShtrihProcess()
        {
            ///печатаем все с колличеством указанном в количестве
            if (cbSelRows.SelectedIndex == 0)
            {
                foreach (DataGridViewRow row in dgvPartiesList.Rows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    string price = dr.RetailPrice.ToString();
                    //Util.StrihWapper.PrintBarKode(30, 20, dr.RestQntty, 1, KString(dr.FullName), price, "Arial", dr.BarCode);
                    Util.StrihWapper.ZebraPrintBarcode(dr.RestQntty, KString(dr.FullName), price, dr.BarCode);
                }
            }
            ///печатаем выделенные с диологом по каждой отдельно
            else
            {
                if (dgvPartiesList.SelectedRows.Count < 1)
                {
                    MessageBox.Show("Необходимо выбрать хотябы 1 партию", "Выберите партию", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                foreach (DataGridViewRow row in dgvPartiesList.SelectedRows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    ShtrihInfo si = new ShtrihInfo(dr);
                    si.ShowDialog(this);
                    DialogResult dro = si.DialogResult;
                    if (dro == DialogResult.OK)
                    {
                        if (si.Count == 0)
                        {
                            si.Close();
                            continue;
                        }
                        string price = dr.RetailPrice.ToString();
                       // Util.StrihWapper.PrintBarKode(30, 20, si.Count, 1, KString(dr.FullName), price, "Arial", dr.BarCode);
                        Util.StrihWapper.ZebraPrintBarcode(si.Count, KString(dr.FullName), price, dr.BarCode);
                    }
                    si.Close();
                }
            }
        }
        /// <summary>
        /// печатаем штрихэтикетки
        /// </summary>
        private void ShtrihProcess()
        {
            ///печатаем все с колличеством указанном в количестве
            if (cbSelRows.SelectedIndex == 0)
            {
                foreach (DataGridViewRow row in dgvPartiesList.Rows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    string price = dr.RetailPrice.ToString();                    
                    Util.StrihWapper.PrintBarKode(30, 20, dr.RestQntty, 1, KString(dr.FullName),price, "Arial", dr.BarCode);
                }
            }
            ///печатаем выделенные с диологом по каждой отдельно
            else
            {
                if(dgvPartiesList.SelectedRows.Count<1)
                {
                    MessageBox.Show("Необходимо выбрать хотябы 1 партию","Выберите партию",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return;
                }
                foreach (DataGridViewRow row in dgvPartiesList.SelectedRows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    ShtrihInfo si = new ShtrihInfo(dr);
                    si.ShowDialog(this);
                    DialogResult dro = si.DialogResult;
                    if (dro == DialogResult.OK)
                    {
                        if (si.Count == 0)
                        {
                            si.Close();
                            continue;
                        }
                    string price = dr.RetailPrice.ToString();  
                        Util.StrihWapper.PrintBarKode(30, 20, si.Count, 1, KString( dr.FullName),price, "Arial", dr.BarCode);
                    }
                    si.Close();
                }
            }
        }
        private string KString(string s)
        {
            if (s.Length < 50)
                return s;
            return s.Substring(0, 50);
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            List<Int32> partyIDs = new List<int>();
            if (cbSelRows.SelectedIndex == 0)
            {
                foreach (DataGridViewRow row in dgvPartiesList.Rows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    Int32 i = dr.PartyId;
                    partyIDs.Add(i);
                }
            }
            else
            {
                if (dgvPartiesList.SelectedRows.Count < 1)
                {
                    MessageBox.Show("Требуется выделить хотябы одну строку", "Выделите строку", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                foreach (DataGridViewRow row in dgvPartiesList.SelectedRows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    Int32 i = dr.PartyId;
                    partyIDs.Add(i);
                }
            }
            string str = CreateXML(partyIDs).OuterXml;
            ReceptionGoods.ZennikOnly szForm = new ReceptionGoods.ZennikOnly(CreateXML(partyIDs).OuterXml);
            szForm.Show();
        }
    }
}